﻿using System.Linq;
using Microsoft.SharePoint.Client;
using ProvisioningLibrary.Models;

namespace ProvisioningLibrary.Handlers
{
    public class ContentTypeHandler : Handler
    {
        protected ContentType _type;
        protected CustomerDetails _details;

        protected void AddContentType(ClientContext context)
        {
            List pages = context.Web.Lists.GetByTitle("Site Pages");

            ListItemCollection existingPages = pages.GetItems(CamlQuery.CreateAllItemsQuery());
            context.Load(existingPages, items => items.Include(i => i.DisplayName).Where(o => o.DisplayName == "Home"));
            context.ExecuteQuery();

            if (existingPages.Count > 0)
            {
                ListItem item = existingPages.FirstOrDefault();
                context.Load(item);
                context.ExecuteQuery();

                ApplyContentType(context, item, _type.Id);

                AssignValues(context, item);
            }
        }

        private void ApplyContentType(ClientContext context, ListItem item, ContentTypeId id)
        {
            item["ContentTypeId"] = _type.Id;
            item.Update();
            context.ExecuteQuery();
        }

        private void AssignValues(ClientContext context, ListItem item)
        {
            item["Relationship"] = CheckString(_details.Relationship);
            item["MacId"] = _details.MaconomyId;
            item["Customer"] = CheckString(_details.Customer);
            item["Industry"] = CheckString(_details.Industry);
            item["CustomerResponsible"] = CheckString(_details.CustomerResponsible);
            item["CustomerCategory"] = CheckString(_details.Category);
            item["CustomerPhone"] = CheckString(_details.Phone);
            item["CustomerAddress"] = CheckString(_details.Address);
            item.Update();
            context.ExecuteQuery();
        }

        private string CheckString(string str)
        {
            if (string.IsNullOrEmpty(str))
                return "";
            return str;
        }
    }
}